import {
    Box,
    Button,
    ButtonGroup,
    Drawer,
    DrawerBody,
    DrawerCloseButton,
    DrawerContent, DrawerFooter,
    DrawerHeader,
    DrawerOverlay,
    FormLabel,
    Input,
    Popover,
    PopoverArrow,
    PopoverBody,
    PopoverCloseButton,
    PopoverContent,
    PopoverFooter,
    PopoverHeader,
    PopoverTrigger,
    Stack,
    useColorModeValue, useToast
} from "@chakra-ui/react";
import ManageSearchBar from "../../components/ManageSearchBar.jsx";
import {CheckIcon, DeleteIcon, EditIcon} from "@chakra-ui/icons";
import {findByName, getAllDoctor, getAllDoctorPage, getDoctorCount, saveDoctor} from "../../api/doctor.js";
import {handleResult, handleResultNoRoute} from "../../api/result.js";
import React, {useEffect, useState} from "react";
import {DoctorShowSearchBar} from "../../components/DoctorShowSearchBar.jsx";
import {useNavigate} from "react-router-dom";
import {useAuth} from "../../hooks/index.js";
import {studentOrder} from "../../api/student.js";

export function DoctorShowPage() {
    const navigator = useNavigate()
    const toast = useToast()
    const {authInfo} = useAuth()

    // 数据获取
    const [doctors, setDoctors] = useState([])
    const [total, setTotal] = useState([])
    useEffect(() => {
        // 请求数据
        getAllDoctorPage({page: 0, size: 6}).then((data) => {
            setDoctors(data.data)
        })
        getDoctorCount().then(r => setTotal(r.data))
    }, []);


    // SearchBar states
    const [value, setValue] = useState('')
    let timer = new Date()
    const [startDate, setStartDate] = useState(timer.toLocaleDateString())
    const [endDate, setEndDate] = useState(timer.toLocaleDateString())

    let searchItem = {
        placeholder: '医生名称',
        value,
        onChange: (e) => {
            setValue(e.target.value)
        },
        onClick: (e) => {
            if (value === '') {
                getAllDoctor().then(r => {
                    handleResultNoRoute(r, toast, '', '查询成功')
                    setDoctors(r.data)
                })
                return
            }
            findByName(value).then(r => {
                handleResultNoRoute(r, toast, '', '查询成功')
                setDoctors(r.data)
            })
        }
    }
    let dateSearchItem = {
        onChange: (date, dateString) => {
            console.log(date, dateString)
            setStartDate(dateString[0])
            setEndDate(dateString[1])
        },
        onClick: (e) => {
            console.log(startDate, endDate)
        }
    }
    // 当前页码
    const [curIdx, setCurIdx] = useState(0);
    let pageSearchItem = {
        total: (Math.floor(total / 6) + 1), curIdx,
        onChange: (e) => {
            setCurIdx(e.target.value)
        },
        onLeftClick: () => {
            console.log(curIdx)
            if (curIdx > 1) {
                setCurIdx((curIdx - 1))
                return
            }
            toast({
                title: `已到达第一页!`,
                status: 'warning',
                position: 'top',
                isClosable: true,
            })
        },
        onRightClick: () => {
            if (curIdx < (Math.floor(total / 6) + 1)) {
                setCurIdx((curIdx + 1))
                return
            }
            toast({
                title: `已到达最后一页!`,
                status: 'warning',
                position: 'top',
                isClosable: true,
            })
        },
        onClick: () => {
            getAllDoctorPage({page: curIdx, size: 6})
                .then(r => {
                    handleResultNoRoute(r, toast, '', '查询成功')
                    setDoctors(r.data)
                })
        }
    }

    // 预约
    const handleOrderClick = (id) => {
        console.log(id)
        console.log(authInfo.profile.student.id)
        studentOrder({
            sid: authInfo.profile.student.id,
            did: id
        }).then(r => handleResult(r, toast, "", "预订成功"))
    }

    return (
        <>
            <Stack
                align={'start'}
                justify={'start'}
                mb={6}
                className={useColorModeValue('', 'dark')}
                spacing={4}
                >
                <DoctorShowSearchBar
                    pageSearchItem={pageSearchItem}
                    searchItem={searchItem}
                    dateSearchItem={dateSearchItem}/>
                <div className={"table-container"}>
                    <table className="table table-hover mt-3">
                        <thead>
                        <tr>
                            <th>名称</th>
                            <th>入职时间</th>
                            <th>问诊总数</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        {
                            doctors.map((item) => (
                                <tr key={item.id}>
                                    <td>{item.name}</td>
                                    <td>{item.createTime}</td>
                                    <td>{item.number}</td>
                                    <td>
                                        <Stack direction='row' spacing={4}>
                                            <Popover
                                                placement='right'
                                                closeOnBlur={false}
                                            >
                                                <PopoverTrigger>
                                                    <Button
                                                        leftIcon={<CheckIcon/>} size='sm'
                                                        colorScheme='green' variant='solid'>
                                                        预约
                                                    </Button>
                                                </PopoverTrigger>
                                                <PopoverContent>
                                                    <PopoverHeader fontWeight='semibold'>Confirmation</PopoverHeader>
                                                    <PopoverArrow/>
                                                    <PopoverCloseButton/>
                                                    <PopoverBody>
                                                        你确定要预约该医生吗?
                                                    </PopoverBody>
                                                    <PopoverFooter display='flex' justifyContent='flex-end'>
                                                        <ButtonGroup size='sm'>
                                                            <Button
                                                                onClick={() => handleOrderClick(item.id)}
                                                                colorScheme='green'>确认</Button>
                                                        </ButtonGroup>
                                                    </PopoverFooter>
                                                </PopoverContent>
                                            </Popover>
                                        </Stack>
                                    </td>
                                </tr>
                            ))
                        }
                        </tbody>
                    </table>
                </div>
            </Stack>
        </>
    )
}